import { IJson, IResAndReqFields, IField } from "../../interface/type"
import utilTool from "../../util/tool"
import { config } from '../../config'



function getSchema(children: IField[], parentKey: string): string[] {
  let arr: string[] = []
  if (parentKey) {
    parentKey = parentKey + '.'
  }
  for (const item of children) {
    if (typeof item !== "object" || item.name === 'pageResponse') {
      continue
    }
    const currentKey = parentKey + item.name
    if (item && item.children && item.children.length > 0) {
      arr = arr.concat(getSchema(item.children, currentKey))
    } else if (item) {
      const upServerName = utilTool.firstLower(utilTool.lineToUp(config.serverName))
      utilTool.updateCompProp(item, item.name, upServerName)
      const descArr = item?.description ? utilTool.getDescription(item?.description) : ['', '']
      arr.push(`
      {
        field: '${currentKey}',
        label: '${descArr[0]}:',${descArr[1]}
        component: '${item.component}',
        ${item.compProps}
      },`)
    }
  }
  return arr
}

// 根据请求参参数生成搜索条件配置
function getSchemas(json: IResAndReqFields): string {
  if (!json?.request) {
    return ''
  }
  const cjson = JSON.parse(JSON.stringify(json.request))
  return getSchema(cjson, '').join('')
}

// 根据字段设置格式化
function getFormatterStr(children: IField, lowServerName: string): string {
  let formatterStr = ''
  if (children.EnumOptionName) {
    const enumKey = utilTool.firstUp(children.name) + 'Enum'
    formatterStr = `formatter: (row, cloumn, value) => {
          return util.getEnumLabel(${lowServerName}Enum.${enumKey}, value)
        },`
  } else if ((children.type.toLowerCase() === 'long' || (children.type === 'integer')) && utilTool.checkStrIncludeKeyWord(children.description || '', ['时间'])) {
    // 如果是日期＼时间
    formatterStr = `// formatter: (row, cloumn, value) => { return value ? util.formatShortDate(value, 'YYYY-MM-DD hh:mm:ss') : '--' }
        formatter: (row, cloumn, value) => { return value ? util.formatDate(value, 'YYYY-MM-DD hh:mm:ss') : '--' },
        width: '160px',`
  } else if ((children.type.toLowerCase() === 'long' || (children.type === 'integer')) && utilTool.checkStrIncludeKeyWord(children.description || '', ['日'])) {
    // 如果是日期＼时间
    formatterStr = `// formatter: (row, cloumn, value) => { return value ? util.formatShortDate(value, 'YYYY-MM-DD hh:mm:ss') : '--' }
        formatter: (row, cloumn, value) => { return value ? util.formatDate(value) : '--' },
        width: '160px',`
  } else if (children.description && utilTool.checkStrIncludeKeyWord(children.description, ['金额'])) {
    // 如果是金额就格式化一下显示为两位小数
    formatterStr = `formatter: (row, cloumn, value) => {
      return util.formatterNumber(value)
    },`
  }
  return formatterStr
}

function getCol(children: IField[], parentKey: string, lowServerName: string, tableDatakey: string): string[] {
  let arr:string[] = []
  if (parentKey) {
    parentKey = parentKey + '.'
  }
  for (const item of children) {
    if (typeof item !== "object" || item.name === 'pageResponse') {
      // 排除非对象，以及排除值为数组对象
      continue
    }
    let currentKey = ''
    if (tableDatakey !== item.name) {
      currentKey = parentKey + item.name
    }
    if (item && item.children && item.children.length > 0) {
      arr = arr.concat(getCol(item.children, currentKey, lowServerName, tableDatakey))
    } else if (item) {
      const formatterStr = getFormatterStr(item, lowServerName)
      const descArr = utilTool.getDescription(item?.description || '')
      arr.push(`
      {
        prop: '${currentKey}',
        label: '${descArr[0]}',${descArr[1]}
        // width: '110px',
        ${formatterStr}
      },`)
    }
  }
  return arr
}

// 获取表格列
function getCols(json: IJson, tableDatakey: string, lowServerName: string): string {
  if (!tableDatakey || !json?.response) {
    return ''
  }
  const arr: string[] = getCol(json?.response, '', lowServerName, tableDatakey)
  // const columns = json
  return arr.join('')
}

// const PAGE_KEYS = ['current', 'hitCount', 'pages', 'searchCount', 'size', 'total']

// 获取返回值中表格数据的key, 规则：1．看'records' 是否存在，如果存在就返回'records'(这一规则与后台约定)　2.是排除分页面外，取第一个类型为数组的数据
function getRecordsKey(responses: IField[]): string {
  console.log('----------getRecordsKey---------------------', JSON.stringify(responses))
  if (!responses) {
    console.log('出错了，列表接口返回结果，不符合规则，请检查接口是否正确')
    throw new Error('出错了，列表接口返回结果，不符合规则，请检查接口是否正确');
  }
  for (const item of responses) {
    if (item.name === 'pageResponse') continue
    if (item.type === 'list' && item.children && item.children?.length > 0) {
      return item.name
    }
  }
  return 'pageList'
}

export function listDataTemp(json: IResAndReqFields, pageConfig: IJson) {
  console.log('开始读取数据，准备生成', pageConfig.list.fileName+'.data.js')
  const enumFileName: string = utilTool.upToLine(`co-${utilTool.firstLower(config.serverName)}Enum`)
  const upServerName = utilTool.lineToUp(config.serverName)
  const lowServerName = utilTool.firstLower(upServerName)
  const tableDatakey = getRecordsKey(json.response)
  return `import ${lowServerName}Enum from '@/assets/js/enum/${enumFileName}'
import util from '@/assets/js/co-util'
export function tableConfig () {
  return {
    showIndex: true, // 显示序号
    listResultName: '${tableDatakey}', // 这里是列表接口返回表格数据的key，能让后台统一最好，不能统一也需要有一个规则，否则生成后需要改
    searchForm: {
      baseColProps: { span: 8 },
      ${pageConfig.list?.exportFile?.apiUrl ? '' : '// '}showExportButton: true,
      // hasExportPermission: () => { // 是否有导出的权限
      //   return this.hasPermission('FUN_1_')
      // },
      schemas: [
        ${getSchemas(json)}
      ]
    },
    columns: [
      ${getCols(json, tableDatakey, lowServerName)}
    ]
  }
}
  `
}
